$(function() {
	// 页面控件
	var $iChecks = $('.i-checks'); // 页面中的所有checkbox（iCheck）
	
	var $byShelfForm = $('#byShelfForm'); // 按机架表单
	var $url1_shelf = $('#url1_shelf');
	var $username1_shelf = $('#username1_shelf');
	var $password1_shelf = $('#password1_shelf');
	var $mode1_shelf = $('#mode1_shelf');
	var $url2_shelf = $('#url2_shelf');
	var $username2_shelf = $('#username2_shelf');
	var $password2_shelf = $('#password2_shelf');
	var $mode2_shelf = $('#mode2_shelf');
	var $url3_shelf = $('#url3_shelf');
	var $username3_shelf = $('#username3_shelf');
	var $password3_shelf = $('#password3_shelf');
	var $mode3_shelf = $('#mode3_shelf');
	var $btnReset_shelf = $('#btnReset_shelf'); // 按机架：清空按钮
	var $btnSave_shelf = $('#btnSave_shelf'); // 按机架：提交按钮
	var $shelfTip_shelf = $('#shelfTip_shelf'); // 按机架：未选择机架时的提示
	
	var $byIPForm = $('#byIPForm'); // 按IP表单
	var $ipListTip_ip = $('#ipListTip_ip'); // 按IP：未选择IP文件时的提示
	
	var $mode1_ip = $('#mode1_ip');
	var $mode2_ip = $('#mode2_ip');
	var $mode3_ip = $('#mode3_ip');
	
	var $btnImportIpList_ip = $('#btnImportIpList_ip'); // 按IP：从文件导入IP按钮
	var $btnReset_ip = $('#btnReset_ip'); // 按IP：清空按钮
	var $btnSave_ip = $('#btnSave_ip'); // 按IP：提交按钮
	
	var uploader; // 按IP：IP文件选择
	var $fileNameDisplay = $('#fileNameDisplay'); // 按IP：显示所选文件名
	
	var $shelfTable = $('#shelfTable'); // 机架选择表格
	var $inputShelfName = $('#inputShelfName'); // 机架选择表格查询条件：机架名称
	var $inputShelfIPBlock = $('#inputShelfIPBlock'); // 机架选择表格查询条件：IP段
	var $chosenShelfAreaList = $('#chosenShelfAreaList'); // 机架选择表格查询条件：所属矿区
	var $chosenShelfTypeList = $('#chosenShelfTypeList'); // 机架选择表格查询条件：矿机类型
	var $chosenShelfEnableList = $('#chosenShelfEnableList'); // 机架选择表格查询条件：可用状态
	
	// 1：按机架；2：按IP
	var by = 0;
	
	initWidgets();
	initLinstener();
	initValidators();
	initUploader();
	
	function doSubmitByShelf() {
		var data = $byShelfForm.serializeObject();
		var pools = [
		             {
		            	 url: data.url1,
		            	 username: data.username1,
		            	 password: data.password1,
		            	 mode: data.mode1
		             },
		             {
		            	 url: data.url2,
		            	 username: data.username2,
		            	 password: data.password2,
		            	 mode: data.mode2
		             },
		             {
		            	 url: data.url3,
		            	 username: data.username3,
		            	 password: data.password3,
		            	 mode: data.mode3
		             }
		            ];
		var shelfs = $shelfTable.bootstrapTable('getSelections');
		var job = {
				mode: data.mode,
				pools: pools,
				shelfs: shelfs
		};
		var paramData = JSON.stringify(job);
		doPostByShelf(paramData);
	}
	
	function doSubmitByIP() {
		var data = $byIPForm.serializeObject();
		doPostByIP(data);
	}
	
	function doPostByShelf(data) {
		loadmask.showProgress('正在提交，请稍后...');
		$.ajax({
			url: 'setups/shelf',
			type: 'POST',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: data,
			success: function(result) {
				if (result.success) {
					toastr.success(result.message, '提交成功');
				} else {
					toastr.error(result.message, '提交失败');
				}
				loadmask.hide();
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
				loadmask.hide();
			}
		});
	}
	
	function doPostByIP(data) {
		uploader.option('formData', {
			mode: data.mode,
			url1: data.url1,
			username1: data.username1,
			password1:data.password1,
			mode1: data.mode1,
			url2: data.url2,
			username2: data.username2,
			password2:data.password2,
			mode2: data.mode2,
			url3: data.url3,
			username3: data.username3,
			password3:data.password3,
			mode3: data.mode3
		});
		loadmask.showProgress('正在提交，请稍后...');
		uploader.upload();
	}
	
	// 初始化表单验证
	function initValidators() {
		var validIcon = "<i class='fa fa-times-circle'></i> ";
		$byShelfForm.validate({
			rules: {
				url1: {required: true},
				username1: {required: true},
				//password1: {required: true},
				url2: {required: true},
				username2: {required: true},
				//password2: {required: true},
				url3: {required: true},
				username3: {required: true}/*,
				password3: {required: true}*/
			},
			messages: {
				url1: '请填写正确的URL。',
				username1: '请填写正确的Worker',
				password1: '请填写正确的Password',
				url2: '请填写正确的URL。',
				username2: '请填写正确的Worker',
				password2: '请填写正确的Password',
				url3: '请填写正确的URL。',
				username3: '请填写正确的Worker',
				password3: '请填写正确的Password'
			}
		});
		$byIPForm.validate({
			rules: {
				url1: {required: true},
				username1: {required: true},
				//password1: {required: true},
				url2: {required: true},
				username2: {required: true},
				//password2: {required: true},
				url3: {required: true},
				username3: {required: true}/*,
				password3: {required: true}*/
			},
			messages: {
				url1: '请填写正确的URL。',
				username1: '请填写正确的Worker',
				password1: '请填写正确的Password',
				url2: '请填写正确的URL。',
				username2: '请填写正确的Worker',
				password2: '请填写正确的Password',
				url3: '请填写正确的URL。',
				username3: '请填写正确的Worker',
				password3: '请填写正确的Password'
			}
		});
	}
	
	var emptyPools = {url1:'',username1:'',password1:'',url2:'',username2:'',password2:'',url3:'',username3:'',password3:''};
	function initLinstener() {
		// 按机架：清空按钮
		$btnReset_shelf.on('click', function() {
			$.each(emptyPools, function (key, value) {
				$('#' + key + '_shelf').val(value);
			});
		});
		
		// 按机架：提交按钮
		$btnSave_shelf.on('click', function() {
			var valid = $byShelfForm.validate().form();
			var selections = $shelfTable.bootstrapTable('getSelections');
			if (!selections || selections.length == 0) {
				valid &= false;
				$shelfTip_shelf.show();
			} else {
				$shelfTip_shelf.hide();
			}
			if (!valid) {
				return;
			}
			doSubmitByShelf();
		});
		
		// 按IP：清空按钮
		$btnReset_ip.on('click', function() {
			$.each(emptyPools, function (key, value) {
				$('#' + key + '_ip').val(value);
			});
			$fileNameDisplay.text('');
			uploader.reset();
		});
		
		// 按IP：提交按钮
		$btnSave_ip.on('click', function() {
			var valid = $byIPForm.validate().form();
			var files = uploader.getFiles();
			if (!files || files.length <= 0) {
				valid &= false;
				$ipListTip_ip.show();
			}
			if (!valid) {
				return;
			}
			doSubmitByIP();
		});
		
		// 机架查询条件：值改变时刷新数据表格
		$inputShelfName.on('change', function() {
			$shelfTable.bootstrapTable('refresh');
		});
		$inputShelfIPBlock.on('change', function() {
			$shelfTable.bootstrapTable('refresh');
		});
		$chosenShelfAreaList.on('change', function() {
			$shelfTable.bootstrapTable('refresh');
		});
		$chosenShelfTypeList.on('change', function() {
			$shelfTable.bootstrapTable('refresh');
		});
		$chosenShelfEnableList.on('change', function() {
			$shelfTable.bootstrapTable('refresh');
		});
	}
	
	// 查询条件中的 “矿机类型”下拉列表框-添加数据
	function initChosenTypeData(selection) {
		$.ajax({
			url: 'types',
			type: 'GET',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			success: function(result) {
				if (result.success) {
					$chosenShelfTypeList.empty();
					$chosenShelfTypeList.append($('<option></option>').val('').html(''));
					var allDatas = result.rows;
					for (var i = 0; i < allDatas.length; i++) {
						var data = allDatas[i];
						$chosenShelfTypeList.append($('<option></option>').val(data.id).html(data.name));
					}
					$chosenShelfTypeList.val(selection);
					$chosenShelfTypeList.chosen('destroy').chosen({allow_single_deselect: true, width:'100px'});
				} else {
					toastr.error(result.message, '矿机类型下拉列表数据获取失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '矿机类型下拉列表数据获取失败');
			}
		});
	}
	
	// 查询条件中的 “所属矿区”下拉列表-添加数据
	function initChosenAreaData(selection) {
		$.ajax({
			url: 'areas',
			type: 'GET',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			success: function(result) {
				if (result.success) {
					$chosenShelfAreaList.empty();
					$chosenShelfAreaList.append($('<option></option>').val('').html(''));
					var allDatas = result.rows;
					for (var i = 0; i < allDatas.length; i++) {
						var data = allDatas[i];
						$chosenShelfAreaList.append($('<option></option>').val(data.id).html(data.name));
					}
					$chosenShelfAreaList.val(selection);
					$chosenShelfAreaList.chosen('destroy').chosen({allow_single_deselect: true, width:'150px'});
				} else {
					toastr.error(result.message, '矿区下拉列表数据获取失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '矿区下拉列表数据获取失败');
			}
		});
	}
	
	// 初始化页面控件
	function initWidgets() {
		$iChecks.iCheck({checkboxClass:'icheckbox_square-green',radioClass:'iradio_square-green'});
		
		$mode1_shelf.chosen({allow_single_deselect: true, width:'100%'});
		$mode2_shelf.chosen({allow_single_deselect: true, width:'100%'});
		$mode3_shelf.chosen({allow_single_deselect: true, width:'100%'});
		$mode1_ip.chosen({allow_single_deselect: true, width:'100%'});
		$mode2_ip.chosen({allow_single_deselect: true, width:'100%'});
		$mode3_ip.chosen({allow_single_deselect: true, width:'100%'});
		
		initShelfTable();
		initChosenTypeData('');
		initChosenAreaData('');
	}
	
	function initShelfTable() {
		// 查询条件：“所属矿区”下拉列表-初始化
		$chosenShelfAreaList.chosen({allow_single_deselect: true, width:'150px'});
		// 查询条件：“矿机类型”下拉列表框-初始化
		$chosenShelfTypeList.chosen({allow_single_deselect: true, width:'100px'});
		// 查询条件：“可用状态”下拉列表框
		$chosenShelfEnableList.val('1');
		$chosenShelfEnableList.chosen({allow_single_deselect: true, width:'80px'});
		
		// 表格
		$shelfTable.bootstrapTable({
			height: 300,
			url: 'shelfs',
			queryParams: function(params) { // 构建表格查询参数
				var areaId = $chosenShelfAreaList.val();
				var minerTypeId = $chosenShelfTypeList.val();
				var name = $inputShelfName.val();
				var ipBlock = $inputShelfIPBlock.val();
				var enable = null;
				var enableVal = $chosenShelfEnableList.val();
				if (enableVal == '1') {
					enable = true;
				} else if (enableVal == '-1') {
					enable = false;
				} else {
					enable = null;
				}
				var params = {
								areaId: areaId,
								minerTypeId: minerTypeId,
								name: name,
								ipBlock: ipBlock,
								enable: enable,
								sort: params.sort,
								order: params.order
							};
				return params;
			},
			idField: 'id',
			//clickToSelect: true,
			pagination: false,
			sidePagination: 'server',
			showRefresh: true,
			showToggle: true,
			showColumns: true,
			toolbar: '#shelfTableToolbar',
			iconSize: 'outline',
			icons: {
				paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
	            paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
	            refresh: 'glyphicon-repeat',
				toggle: 'glyphicon-list-alt',
				columns: 'glyphicon-list',
	            detailOpen: 'glyphicon-plus icon-plus',
	            detailClose: 'glyphicon-minus icon-minus'
			},
			rowStyle: function(row, index) { // 机架所属矿区不可用时高亮显示整行
				if (row.areaEnable == false) {
					return {classes: 'warning'};
				}
				return {};
			},
			columns: [
				{
					field: 'checkStatus',
					checkbox: true,
					align: 'center'
				},
				{
					field: 'id',
					title: 'ID',
					align: 'center',
					sortable: true,
					visible: false
				},
				{
					field: 'areaName',
					title: '所属矿区',
					halign: 'center',
					align: 'left',
				},
				{
					field: 'name',
					title: '机架名称',
					halign: 'center',
					align: 'left',
					sortable: true
				},
				{
					field: 'minerTypeName',
					title: '矿机类型',
					halign: 'center',
					align: 'left',
				},
				{
					field: 'ipBlock',
					title: 'IP段',
					halign: 'center',
					align: 'left',
					sortable: true,
				},
				{
					field: 'ipBeginning',
					title: 'IP起始索引',
					halign: 'center',
					align: 'right',
				},
				{
					field: 'ipEnd',
					title: 'IP结束索引',
					halign: 'center',
					align: 'right',
				},
				{
					field: 'ignores',
					title: '忽略的IP索引',
					halign: 'center',
					align: 'right',
					formatter: function(value, row, index) {
						if (!value) {
							return value;
						}
						return '<button class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="' + value + '">' + value.length + '个</button>'
					}
				},
				{
					field: 'minerCount',
					title: '矿机数量',
					align: 'center',
					align: 'right',
					formatter: function(value, row, index) {
						var end = row.ipEnd ? row.ipEnd : 0;
						var beginng = row.ipBeginning ? row.ipBeginning : 0;
						var ignore = row.ignores ? row.ignores.length : 0;
						return end - beginng + 1 - ignore;
					}
				},
				{
					field: 'enable',
					title: '可用状态',
					align: 'center',
					sortable: true,
					sortName: 'enable',
					formatter: function(value, row, index) {
						return value == true ? '<img src="../img/icon/icon-enabled.png" width="20" height="20" />' : '<img src="../img/icon/icon-disabled.png" width="20" height="20" />';
					}
				},
				{
					field: 'remark',
					title: '备注',
					halign: 'center',
					align: 'left'
				}
			]
		});
	}
	
	// 设置文件上传控件按钮尺寸
	function initUploaderSize() {
		var children = $('#btnFilePicker').children();
		for (var i = 0; i < children.length; i++) {
			$(children[i]).css({width:300, height:38});
		}
	}
	
	// 初始化文件上传
	function initUploader() {
		var fileLimit = 10 * 1024 * 1024; // 10 M
	    uploader = WebUploader.create({
	    	swf: '../js/plugins/webuploader/Uploader.swf',
	    	server: 'setups/ip',
	    	method: 'POST',
	    	pick: {
	    		id: '#btnFilePicker',
	    		multiple: false
	    	},
	        disableGlobalDnd: true,
	        fileNumLimit: 1,
	        fileSizeLimit: fileLimit,
	        fileSingleSizeLimit: fileLimit,
	        accept: {
	        	title: 'Text',
	        	extensions: 'txt',
	        	mimeTypes: 'text/plain'
	        }
	    });
	    
	    initUploaderSize();
	    
	    uploader.on('fileQueued', function(file) {
	    	$fileNameDisplay.text(file.name);
	    	$ipListTip_ip.hide();
	    });
	    
	    uploader.on('beforeFileQueued', function(file) {
	    	uploader.reset();
	    	return true;
	    });
	    
	    uploader.on('error', function(error) {
	    	if ('Q_EXCEED_SIZE_LIMIT' == error) {
	    		toastr.error('所选文件不能大于10M', '文件错误');
	    	}
	    	if ('Q_TYPE_DENIED' == error) {
	    		toastr.error('只能选择txt格式的文本文件', '文件错误');
	    	}
	    });
	    
	    uploader.on('uploadProgress', function(file, percentage) {
	    	loadmask.updateProgress(percentage);
	    });
	    
	    uploader.on('uploadSuccess', function(file, result) {
	    	if (result.success) {
	    		toastr.success(result.message, '提交成功');
	    	} else {
	    		toastr.error(result.message, '提交失败');
	    	}
	    });
	    
	    uploader.on('uploadError', function(file, reason) {
	    	toastr.error(reason, '提交失败');
	    });
	    
	    uploader.on('uploadComplete', function(file) {
	    	uploader.reset();
	    	$fileNameDisplay.text('');
	    	loadmask.hide();
	    });
	}
});